<?php
/**
 * XGPHP 轻量级PHP框架
 * @link http://xgphp.xg3.cn
 * @version 2.0.0
 * @license http://www.apache.org/licenses/LICENSE-2.0
 * @author 讯高科技 <xungaokeji@qq.com>
*/
namespace xg;
use \helper\Arr;
use \helper\File;

class Config {
	protected $app='';
	protected $data=[];
	// 加载配置
	public function load(string $configName){
		$data=[];
		// 检测自定义配置目录
		if(is_file($phpFile=File::path('xg:config',$configName.'.php'))){
			$data=include($phpFile);
		}else{
			// 检测框架配置目录
			if(is_file($phpFile=File::path('xg:php','config',$configName.'.php'))){
				$data=include($phpFile);
			}
		}
		return $data;
	}
	// 加载应用配置
	public function setApp(string $app=''){
		$this->app=$app;
		$this->loadAppFiles($this->app);
		return $this;
	}
	// 加载应用配置
	protected function loadAppFiles(string $app=''){
		$data=[];
		$path=File::path('xg:apps',$app?$app:$this->app);
		$files=File::findFiles($path,'php');
		foreach($files as $file){
			$filename=basename($file);
			$configName=substr($filename,0,strlen($filename)-4);
			$data[$configName]=include($file);
		}
		$this->data=Arr::extend($this->data,$data);
	}
	// 获取配置
	public function get($name,$default=null){
		$nameArr=Arr::split($name,'.');
		$configName=$nameArr[0];
		if(!$configName){
			return $default;
		}
		$data=&$this->data;
		if(!isset($data[$configName])){
			$data[$configName]=$this->load($configName);
		}
		if($nameArr[1]){
			$value=Arr::get($data,$nameArr);
			return is_null($value)?$default:$value;
		}
		return isset($data[$configName])?$data[$configName]:$default;
	}
	// 修改配置
	public function set($name,$value){
		$nameArr=Arr::split($name,'.');
		Arr::set($this->data,$nameArr,$value);
	}
}
